/**
 * @author yinyuejia
 * @file 封装工具常用方法
 * @include 深拷贝 copy;数组扁平化 flatMap;驼峰转下划线 toCamelCase;判断不为无效值 ensureNotNull
 */

import typeUtil from './type';

const pro = {
  // 深拷贝 可用loadsh.cloneDeep代替
  copy: (function () {
    return function innerCopy(data: any) {
      const t = typeUtil.getType(data);
      let o: any;

      if (t === 'array') {
        o = [];
        for (let i = 0; i < data.length; i++) {
          o.push(innerCopy(data[i]));
        }
      } else if (t === 'object') {
        o = {};
        for (const i in data) {
          // eslint-disable-line
          if (Object.prototype.hasOwnProperty.call(data, i)) {
            o[i] = innerCopy(data[i]);
          }
        }
      } else {
        return data;
      }
      return o;
    };
  })(),
  // 数组扁平化 可用loadsh.cloneDeep代替
  flatMap: (function () {
    return function innerMap(arr: any) {
      const newArr: any = [];
      arr.forEach((item: any) => {
        newArr.push(item);
        if (item.children && item.children.length > 0) {
          newArr.push(...innerMap(item.children));
        }
      });
      return newArr;
    };
  })(),
  // 驼峰转下划线
  toCamelCase(s: any) {
    return s.replace(/([A-Z])/g, '_$1').toLowerCase();
  },
  // 判断不为无效值
  ensureNotNull(value: any) {
    if (typeUtil.isNull(value) || typeUtil.isUndefined(value)) {
      return false;
    }
    return value;
  },
};
export default pro;

// 递归将route格式转为menu格式
export function routerToMenu(routerList: Array<any>) {
  const res: any = [];
  let obj: any = {};
  routerList.map((item) => {
    obj = {};
    obj.code = item.name || '';
    obj.url = item.path ? '/' + item.path : '';
    obj.name = item.meta.title || '';
    obj.order = item.meta.order || 0;
    obj.icon = item.meta.icon || '';
    obj.component = item.component || {};
    obj.meta = item.meta;
    if (item.children && item.children.length > 0) {
      obj.children = routerToMenu(item.children);
    }
    res.push(obj);
  });
  console.log(res);

  return res;
}
// 随机字符串
export function randomString(length: any) {
  const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = length; i > 0; --i) {
    result += str[Math.floor(Math.random() * str.length)];
  }
  return result;
}
